<template>
	<view class="container">
		<view class="toolbar">
			<button @tap="chooseImage">选择图片</button>
			<button @tap="exportImage">导出图片</button>
			<button @tap="cleanClick">一键清除</button>
		</view>
		<canvas canvas-id="myCanvas" id="myCanvas" type="2d" @longtap="longtap" @touchstart="handleTouchStart"
			@touchmove="handleTouchMove" @touchend="handleTouchEnd"
			style="width: 750rpx; height: 1000rpx; border: 1px solid #ccc;"></canvas>

		<u-popup v-model="show" border-radius="16" mode="center">
			<view style="width: 550rpx;padding: 20rpx;">
				<view style="text-align: center;font-size: 36rpx;font-weight: 600;" class="">
					输入正确的字
				</view>

				<input type="text" class="inp" v-model="form.cuo" placeholder="请输入" />
				<view class="f f-a-c f-j-c">
					<view @click="addStudet" class="comfig f f-a-c f-j-c">
						确认
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {
		mergedArray,
		getClickedRect,
		goodJuZislList,
		errJuZislList,
		xiuJuZislList,
		biaoDianList
	} from "@/uits/list.js"
	export default {
		data() {
			return {
				form: {
					cuo: ''
				},
				show: false,
				canvasNode: null,
				ctx: null,
				dpr: 1,
				circles: [], // 圆圈列表 {x, y, r}
				bgImgPath: '',
				// canvasWidth: 2736,
				// canvasHeight: 3648,
				canvasWidth: 0,
				canvasHeight: 0,
				// ✅【新增】波浪线数据
				waveLines: [], // 每条波浪线是一个点数组：[[{x, y}, {x, y}...], [...]]
				currentWaveLine: [],
				goodJuZisList: [], //优美的句子 
				errJuZislList: [], //不好的句子
				xiuJuZislList: [], //运用的修饰词
				biaoDianList: [], //标点符号使用错误
				touchStartX: 0,
				touchStartY: 0,
				isMoving: false, // 标记是否滑动中
				moveThreshold: 10, // 移动超过10像素判定为滑动
				isDrawing: false,
				longPressThreshold: 200, // 毫秒，设置为你想要的时间
				longPressTimer: null,
				isLongPress: false,
				canvasDisplayWidth: 0,
				canvasDisplayHeight: 0,
				lineWidth: 10, //波浪线的宽度
				size: 20 //画圈的大小

			}
		},
		onShow() {

			console.log(mergedArray, '898899889');

			uni.getImageInfo({
				src: '/static/2.jpg',
				success: (res) => {
					console.log(res, '111111111111111111111');
					this.canvasWidth = res.width
					this.canvasHeight = res.height
					if (this.canvasWidth > 2000) {
						this.lineWidth = 8 //波浪线的宽度
						this.size = 60 //画圈的大小
					} else {
						this.lineWidth = 4 //波浪线的宽度
						this.size = 25 //画圈的大小
					}

				}
			})
		},
		onReady() {
			// var ctx = wx.createCanvasContext('myCanvas', this)
			const query = wx.createSelectorQuery().in(this)
			query
				.select('#myCanvas')
				.fields({
					node: true,
					size: true
				})
				.exec(res => {
					const canvas = res[0].node
					this.canvasDisplayWidth = res[0].width
					this.canvasDisplayHeight = res[0].height
					console.log(canvas, '00000000000000000000');
					const ctx = canvas.getContext('2d')
					const dpr = uni.getSystemInfoSync().pixelRatio
					canvas.width = this.canvasWidth * dpr
					canvas.height = this.canvasHeight * dpr
					ctx.scale(dpr, dpr)

					this.canvasNode = canvas
					this.ctx = ctx
					this.dpr = dpr

					const img = this.canvasNode.createImage()
					img.src = '/static/2.jpg'
					console.log(img, '1111');

					img.onload = async () => {
						ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight)
						this.goodJuZisList = goodJuZislList
						this.errJuZislList = errJuZislList
						this.xiuJuZislList = xiuJuZislList
						this.biaoDianList = biaoDianList
						this.circles = mergedArray.map(item => {
							return {
								...item,
								r: this.size
							}
						})

						setTimeout(() => {
							this.init()
						}, 500)
						this.redraw()
					}
				})
		},
		methods: {
			init() {
				let ctx = this.ctx
				// 优美的句子
				this.goodJuZisList.forEach(item => {
					item.list.forEach((ite, ind) => {
						if (ind == 0) {
							this.drawWaveLine(ctx, ite.lb.x, ite.lb.y, ite.rb.x + 20, ite.rb.y, 10, 2,
								'red', item
								.obj.num);
						} else {
							this.drawWaveLine(ctx, ite.lb.x, ite.lb.y, ite.rb.x + 20, ite.rb.y, 10, 2,
								'red');
						}
					})
				})
				// 不好的句子
				this.errJuZislList.forEach(item => {
					item.list.forEach((ite, ind) => {
						if (ind == 0) {
							this.drawWaveLine(ctx, ite.lb.x, ite.lb.y, ite.rb.x + 20, ite.rb.y, 10, 2,
								'blue', item
								.obj.num);
						} else {
							this.drawWaveLine(ctx, ite.lb.x, ite.lb.y, ite.rb.x + 20, ite.rb.y, 10, 2,
								'blue', '');
						}
					})
				})
				// 运用修饰语句
				this.xiuJuZislList.forEach(item => {
					item.list.forEach((ite, ind) => {
						if (ind == 0) {
							this.drawWaveLine(ctx, ite.lb.x, ite.lb.y, ite.rb.x + 20, ite.rb.y, 10, 2,
								'red', item
								.obj.num);
						} else {
							this.drawWaveLine(ctx, ite.lb.x, ite.lb.y, ite.rb.x + 20, ite.rb.y, 10, 2,
								'red', '');
						}
					})
				})
				// this.drawWaveLine(ctx, 842, 1477, 892, 1477, 10, 2);
				// this.drawWaveLine(ctx, 899, 1477, 949, 1477, 10, 2);
				// this.drawWaveLine(ctx, 956, 1477, 997, 1477, 10, 2);
				// this.drawWaveLine(ctx, 1004, 1477, 1055, 1477, 10, 2);
			},
			drawWaveLine(ctx, x1, y1, x2, y2, waveHeight = 5, waveCount = 2, color = 'red', num = '') {

				const dx = (x2 - x1) / waveCount
				const dy = (y2 - y1) / waveCount
				let currentX = x1
				let currentY = y1

				ctx.beginPath()
				ctx.moveTo(x1, y1)
				// 绘制序号
				if (num) {
					ctx.font = `bold  ${this.size*2}px Arial`
					ctx.fillStyle = color
					ctx.strokeStyle = color
					ctx.lineWidth = this.lineWidth
					ctx.beginPath()
					ctx.stroke()

					// 2. 如果有正确文字（ cuo.correct）， 绘制在右上方
					const text = num;
					const textX = x1 - 10 + 3; // 圆圈右侧 + 5px 间距
					const textY = y1 - 25 - 3; // 圆圈上方 - 5px 间距

					ctx.fillText(text, textX, textY);

				}
				for (let i = 0; i < waveCount; i++) {
					const cx = currentX + dx / 2
					const cy = currentY + dy / 2 + (i % 2 === 0 ? -waveHeight : waveHeight)
					const nextX = currentX + dx
					const nextY = currentY + dy
					ctx.quadraticCurveTo(cx, cy, nextX, nextY)
					currentX = nextX
					currentY = nextY
				}

				ctx.strokeStyle = color
				ctx.lineWidth = 6
				ctx.stroke()
			},
			// 长安✅【修改】touchStart 开始画波浪线
			longtap(e) {},
			startWaveLine(x, y) {
				this.isDrawing = true
				this.currentWaveLine = [{
					x,
					y
				}]
			},
			// 转换真是宽高
			convertTouchToCanvas(x, y) {
				const realX = x / this.canvasDisplayWidth * this.canvasWidth
				const realY = y / this.canvasDisplayHeight * this.canvasHeight
				return {
					x: realX,
					y: realY
				}
			},
			// ✅【修改】点击圈
			handleTouchStart(e) {

				// const x = e.touches[0].x * this.dpr
				// const y = e.touches[0].y * this.dpr
				const touch = e.touches[0]
				const {
					x,
					y
				} = this.convertTouchToCanvas(touch.x, touch.y)
				this.touchStartX = x
				this.touchStartY = y
				this.isMoving = false
				this.isLongPress = false

				// lzl
				// // 启动长按定时器
				// this.longPressTimer = setTimeout(() => {
				// 	this.isLongPress = true
				// 	this.startWaveLine(x, y) // 👈 自定义长按开始的行为
				// }, this.longPressThreshold)




			},

			// ✅【新增】touchMove 收集滑动路径
			handleTouchMove(e) {
				if (!this.isDrawing) return
				// const x = e.touches[0].x * 2
				// const y = e.touches[0].y * 2
				const touch = e.touches[0]
				const {
					x,
					y
				} = this.convertTouchToCanvas(touch.x, touch.y)
				const dx = Math.abs(x - this.touchStartX)
				const dy = Math.abs(y - this.touchStartY)
				const lastPoint = this.currentWaveLine[this.currentWaveLine.length - 1]
				if (!lastPoint || Math.abs(x - lastPoint.x) > 8 || Math.abs(y - lastPoint.y) > 8) {
					this.isMoving = true
					clearTimeout(this.longPressTimer)
					this.currentWaveLine.push({
						x,
						y
					})
					this.redraw()
				}
				//lzl
				// if (dx > this.moveThreshold || dy > this.moveThreshold) {
				// 	this.isMoving = true
				// 	clearTimeout(this.longPressTimer) // 手指滑动就取消长按
				// }
				// if (this.isLongPress && this.isDrawing) {
				// 	this.currentWaveLine.push({
				// 		x,
				// 		y
				// 	})
				// 	this.redraw()
				// }
			},

			// ✅【新增】touchEnd 保存波浪线
			handleTouchEnd(e) {
				clearTimeout(this.longPressTimer)
				// lzl
				// if (this.isLongPress) {
				// 	// 结束波浪线绘制
				// 	if (this.currentWaveLine.length > 0) {
				// 		this.waveLines.push([...this.currentWaveLine])
				// 		this.currentWaveLine = []
				// 	}
				// 	this.isDrawing = false
				// 	this.redraw()
				// 	return
				// }

				// 否则就是点击圈圈逻辑
				if (!this.isMoving) {
					const x = this.touchStartX
					const y = this.touchStartY
					const radius = this.size
					let found = false
					// 判断是否在指定位置点击
					let n = getClickedRect(x, y)
					// console.log(n, '56555555555555555');
					// return
					for (let i = 0; i < this.circles.length; i++) {
						const c = this.circles[i]
						const dist = Math.sqrt((c.x - x) ** 2 + (c.y - y) ** 2)
						if (dist <= c.r) {
							this.circles.splice(i, 1)
							found = true
							break
						}
					}
					if (!found) {
						this.circles.push({
							...n,
							// x,
							// y,
							r: radius
						})
						this.show = true
					}


					this.redraw()
				}
			},
			cleanClick() {
				const ctx = this.ctx
				const bgImgPath = this.bgImgPath

				// 没有背景图，直接清空圈圈和波浪线
				this.circles = []
				this.waveLines = []
				this.currentWaveLine = []
				const img = this.canvasNode.createImage()
				img.src = '/static/2.jpg'
				img.onload = () => {
					ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight)
					this.drawCircles()
					this.drawWaveLines() // ✅【新增】
				}


			},
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: res => {
						this.bgImgPath = res.tempFilePaths[0]
						this.redraw()
					}
				})
			},

			redraw() {
				const ctx = this.ctx
				const img = this.canvasNode.createImage()
				img.src = '/static/2.jpg'
				img.onload = () => {
					ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight)
					this.drawCircles()
					this.drawWaveLines() // ✅【新增】
				}
				// const img = this.canvasNode.createImage()
				this.drawCircles()
				this.drawWaveLines() // ✅【新增】
				// 绘制线条
				setTimeout(() => {
					this.init()
				}, 500)
			},
			// 圈出错别字点击确认
			addStudet() {

				this.circles[this.circles.length - 1].cuo = {
					type: '错别字',
					zi: this.circles[this.circles.length - 1].zi,
					ziIndex: this.circles[this.circles.length - 1].cuolzl.ziIndex,
					correct: this.form.cuo
				}
				this.show = false
				setTimeout(() => {
					this.init()
				}, 500)
				this.drawCircles()
			},
			drawCircles() {
				const ctx = this.ctx
				// 绘制文字
				ctx.font = `${this.size*2}px Arial`
				ctx.fillStyle = "red"
				ctx.strokeStyle = 'red'
				ctx.lineWidth = this.lineWidth
				for (const c of this.circles) {
					ctx.beginPath()
					ctx.arc(c.x, c.y, c.r, 0, Math.PI * 2)
					ctx.stroke()

					// 2. 如果有正确文字（ cuo.correct）， 绘制在右上方
					if (c.cuo?.correct) {
						const text = c.cuo.correct;
						const textX = c.x + c.r + 3; // 圆圈右侧 + 5px 间距
						const textY = c.y - c.r - 3; // 圆圈上方 - 5px 间距

						ctx.fillText(text, textX, textY);
					}
				}
				for (const c of this.biaoDianList) {
					c.list.forEach(item => {
						ctx.font = `blod ${this.size*2}px Arial`
						ctx.fillStyle = "red"
						ctx.strokeStyle = 'red'
						ctx.beginPath()
						ctx.arc(item.x, item.y, this.size, 0, Math.PI * 2)
						ctx.stroke()

						// 2. 如果有正确文字（ cuo.correct）， 绘制在右上方
						if (c.obj?.correct) {
							const text = c.obj.correct;
							const textX = item.x + this.size + 3; // 圆圈右侧 + 5px 间距
							const textY = item.y - this.size - 3; // 圆圈上方 - 5px 间距

							ctx.fillText(text, textX, textY);
						}

					})
				}
			},

			// ✅【新增】绘制波浪线
			drawWaveLines() {
				const ctx = this.ctx
				ctx.strokeStyle = 'red'
				ctx.lineWidth = this.lineWidth

				const drawWave = (points) => {
					if (points.length < 2) return
					ctx.beginPath()
					for (let i = 0; i < points.length - 1; i++) {
						const p1 = points[i]
						const p2 = points[i + 1]
						const midX = (p1.x + p2.x) / 2
						const midY = (p1.y + p2.y) / 2 + Math.sin(i * 0.5) * 30
						ctx.moveTo(p1.x, p1.y)
						ctx.quadraticCurveTo(midX, midY, p2.x, p2.y)
					}
					ctx.stroke()
				}

				for (let line of this.waveLines) {
					drawWave(line)
				}
				if (this.currentWaveLine.length > 1) {
					drawWave(this.currentWaveLine)
				}
			},

			exportImage() {
				uni.canvasToTempFilePath({
					canvas: this.canvasNode,
					fileType: 'png',
					quality: 1,
					success: res => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								})
							},
							fail: () => {
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								})
							}
						})
					},
					fail: err => {
						console.error('导出失败', err)
					}
				}, this)
			}
		},
		beforeDestroy() {
			if (this.canvasNode) {
				this.canvasNode.removeEventListener('touchstart', this.handleTouchStart)
				this.canvasNode.removeEventListener('touchmove', this.handleTouchMove)
				this.canvasNode.removeEventListener('touchend', this.handleTouchEnd)
			}
		}
	}
</script>

<style>
	.container {
		/* padding: 20rpx; */
	}

	.comfig {
		width: 492rpx;
		height: 84rpx;
		background: #05C490;
		border-radius: 30rpx;
		font-family: SourceHanSansCN, SourceHanSansCN;
		font-weight: 500;
		font-size: 36rpx;
		color: #FFFFFF;
		margin-top: 50rpx;
	}

	.inp {
		border-radius: 20rpx;
		border: 2rpx solid #CCCCCC;
		color: #000;
		padding-left: 20rpx;
		height: 70rpx;
		width: 90%;
		margin-top: 30rpx;
	}

	.inp::placeholder {
		color: #CCCCCC;

	}

	.toolbar {
		display: flex;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	button {
		background-color: #4caf50;
		color: white;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
	}
</style>